package com.hm.base.auto.helper;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.EncryptUtil.AES;
import com.hm.core.SdkConfig;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 上午10:55:09 2017年6月5日
 * @version 1.0
 * @describe 获取当前登录用户相关信息
 */
@Slf4j
public class HmSessionFactory {

	public static Long currentUserId() {
		return Long.valueOf(traceToken()[0]);
	}

	public static Long currentUserLoginTime() {
		return Long.valueOf(traceToken()[1]);
	}

	private static String[] traceToken() {
		try {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			String token = request.getHeader(SdkConfig.REMOTE_CLIENT_AUTHORIZATION);
			if (CommonUtil.isEmpty(token)) {
				token = request.getAttribute(SdkConfig.REMOTE_CLIENT_AUTHORIZATION_DEV).toString();
			}
			return AES.decrypt(token).split(":");
		} catch (Exception e) {
			log.error("token解析失败", e);
			throw ServiceException.warning(ErrorCode.NO_DATA_ACCESS);
		}
	}
}
